<template>
  <div class="czml-container">
    <!-- CZML控制组件 -->
    <div class="czml-control" :class="{ expanded: isPanelExpanded }">
      <!-- 控制图标 -->
      <div class="control-icon" @click="togglePanel" v-if="!isPanelExpanded" title="CZML展示">
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
          <circle cx="12" cy="12" r="10" fill="none" stroke="currentColor" stroke-width="2"/>
          <path d="M12 2v20" stroke="currentColor" stroke-width="2"/>
          <path d="M2 12h20" stroke="currentColor" stroke-width="2"/>
          <path d="M12 6l6 6-6 6" stroke="currentColor" stroke-width="2" fill="none"/>
        </svg>
      </div>

      <!-- CZML控制面板 -->
      <div class="czml-control-panel" v-if="isPanelExpanded">
        <div class="panel-header">
          <h3>CZML展示</h3>
          <div class="close-btn" @click="togglePanel">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <path d="M18 6L6 18M6 6l12 12"></path>
            </svg>
          </div>
        </div>
        
        <!-- 显示控制 -->
        <div class="control-section">
          <div class="legend-item checkbox-label" @click="toggleCZML">
            <input type="checkbox" v-model="isVisible" class="legend-checkbox">
            <span class="checkmark"></span>
            <span class="legend-text">显示CZML数据</span>
          </div>
        </div>
        
        <!-- 信息显示 -->
        <div class="control-section" v-if="isVisible">
          <div class="info-item">
            <span class="info-label">实体数量:</span>
            <span class="info-value">{{ entityCount }}</span>
          </div>
        </div>
        
        <!-- 时间控制 -->
        <div class="control-section" v-if="isVisible">
          <div class="info-item">
            <span class="control-title">时间控制:</span>
            <div class="time-controls">
              <button class="control-btn" @click="togglePlay" :disabled="!isVisible">
                <svg v-if="!isPlaying" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                  <polygon points="5 3 19 12 5 21 5 3"></polygon>
                </svg>
                <svg v-else width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                  <rect x="6" y="4" width="4" height="16"></rect>
                  <rect x="14" y="4" width="4" height="16"></rect>
                </svg>
                {{ isPlaying ? '暂停' : '播放' }}
              </button>
            </div>
          </div>
        </div>
        <div class="control-section" v-if="isVisible">
          <div class="info-item">
            <span class="control-title">播放速度:</span>
            <select v-model="playbackSpeed" class="speed-select" @change="updatePlaybackSpeed">
              <option value="0.1">0.1x</option>
              <option value="0.5">0.5x</option>
              <option value="1">1x</option>
              <option value="2">2x</option>
              <option value="5">5x</option>
              <option value="10">10x</option>
              <option value="30">30x</option>
              <option value="60">60x</option>
            </select>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, watch } from 'vue';
import * as Cesium from 'cesium';

const props = defineProps({
  viewer: {
    type: Object,
    required: true
  }
});

const czmlDataSource = ref(null);
const isVisible = ref(false);
const isPanelExpanded = ref(false);
const entityCount = ref(0);
const isPlaying = ref(false);
const playbackSpeed = ref(1);

const togglePanel = () => {
  isPanelExpanded.value = !isPanelExpanded.value;
};

const toggleCZML = async () => {
  if (isVisible.value) {
    await removeCZML();
  } else {
    await loadCZML();
  }
  isVisible.value = !isVisible.value;
};

const loadCZML = async () => {
  try {
    // 清除现有的CZML数据源
    if (czmlDataSource.value) {
      await removeCZML();
    }

    // 加载CZML数据
    const czmlUrl = new URL('../assets/data/satellite.czml', import.meta.url).href;
    czmlDataSource.value = await Cesium.CzmlDataSource.load(czmlUrl);
    props.viewer.dataSources.add(czmlDataSource.value);
    
    // 更新实体数量
    entityCount.value = czmlDataSource.value.entities.values.length;

    // 初始化时钟设置
    if (props.viewer.clock) {
      // 设置时钟范围为CZML数据的时间范围
      const timeInterval = czmlDataSource.value.entities.values.reduce((interval, entity) => {
        if (entity.availability) {
          const entityInterval = entity.availability.getInterval(0);
          if (entityInterval) {
            if (!interval) {
              return entityInterval;
            }
            return Cesium.TimeInterval.fromDateTimes(
              Cesium.JulianDate.minimum(interval.start, entityInterval.start),
              Cesium.JulianDate.maximum(interval.stop, entityInterval.stop)
            );
          }
        }
        return interval;
      }, null);
      
      if (timeInterval) {
        props.viewer.clock.startTime = timeInterval.start;
        props.viewer.clock.stopTime = timeInterval.stop;
        props.viewer.clock.currentTime = timeInterval.start;
      }
      
      // 设置时钟模式
      props.viewer.clock.clockRange = Cesium.ClockRange.LOOP_STOP;
      props.viewer.clock.clockStep = Cesium.ClockStep.SYSTEM_CLOCK_MULTIPLIER;
      props.viewer.clock.multiplier = playbackSpeed.value;
    }

    // 调整视角以显示所有CZML数据
    if (czmlDataSource.value.entities.values.length > 0) {
      const boundingSphere = Cesium.BoundingSphere.fromPoints(
        czmlDataSource.value.entities.values.map(entity => {
          if (entity.position && entity.position.getValue) {
            return entity.position.getValue(props.viewer.clock.currentTime);
          }
          return Cesium.Cartesian3.ZERO;
        })
      );
      props.viewer.camera.flyToBoundingSphere(boundingSphere, {
        duration: 2
      });
    }
  } catch (error) {
    console.error('加载CZML数据失败:', error);
  }
};

const togglePlay = () => {
  if (props.viewer.clock) {
    isPlaying.value = !isPlaying.value;
    props.viewer.clock.shouldAnimate = isPlaying.value;
  }
};

const updatePlaybackSpeed = () => {
  if (props.viewer.clock) {
    props.viewer.clock.multiplier = parseFloat(playbackSpeed.value);
  }
};

const removeCZML = async () => {
  if (czmlDataSource.value) {
    await props.viewer.dataSources.remove(czmlDataSource.value, true);
    czmlDataSource.value = null;
    entityCount.value = 0;
    isPlaying.value = false;
    
    // 重置时钟状态
    if (props.viewer.clock) {
      props.viewer.clock.shouldAnimate = false;
    }
  }
};

// 监听面板关闭事件，自动隐藏CZML
watch(isPanelExpanded, (newVal) => {
  if (!newVal && isVisible.value) {
    toggleCZML();
  }
});

onBeforeUnmount(() => {
  removeCZML();
});
</script>

<style scoped>
.czml-container {
  position: absolute;
  top: 180px;
  right: 20px;
  z-index: 10;
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 10px;
}

.czml-control {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 10px;
  transition: all 0.3s ease;
}

.control-icon {
  width: 32px;
  height: 32px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  box-shadow:
    0 8px 32px rgba(102, 126, 234, 0.4),
    0 0 0 1px rgba(255, 255, 255, 0.1);
  transition: all 0.3s ease;
  color: white;
}

.control-icon:hover {
  transform: translateY(-2px);
  box-shadow:
    0 12px 40px rgba(102, 126, 234, 0.6),
    0 0 0 1px rgba(255, 255, 255, 0.2);
}

.czml-control-panel {
  color: white;
  background: linear-gradient(135deg, rgba(15, 23, 42, 0.15) 0%, rgba(30, 41, 59, 0.15) 100%);
  backdrop-filter: blur(20px);
  border: 1px solid rgba(255, 255, 255, 0.15);
  border-radius: 10px;
  padding: 12px;
  min-width: 240px;
  opacity: 0;
  transform: translateY(20px) scale(0.95);
  pointer-events: none;
  transition: all 0.3s ease;
  box-shadow:
    0 10px 25px rgba(0, 0, 0, 0.15),
    0 0 0 1px rgba(255, 255, 255, 0.08);
}

.czml-control.expanded .czml-control-panel {
  opacity: 1;
  transform: translateY(0) scale(1);
  pointer-events: all;
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  padding-bottom: 10px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.15);
}

.panel-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: white;
}

.close-btn {
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s ease;
  color: white;
}

.close-btn:hover {
  background: rgba(255, 255, 255, 0.1);
}

.control-section {
  margin-bottom: 12px;
}

.control-section:last-child {
  margin-bottom: 0;
}

/* 图例样式 */
.legend-item {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  cursor: pointer;
}

.legend-item:last-child {
  margin-bottom: 0;
}

.checkbox-label {
  position: relative;
  display: flex;
  align-items: center;
  cursor: pointer;
  font-size: 14px;
  color: white;
  user-select: none;
}

.legend-checkbox {
  position: absolute;
  opacity: 0;
  cursor: pointer;
  height: 0;
  width: 0;
}

.checkmark {
  position: relative;
  height: 16px;
  width: 16px;
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.3);
  border-radius: 4px;
  margin-right: 8px;
  transition: all 0.3s ease;
}

.checkbox-label:hover .legend-checkbox ~ .checkmark {
  background: rgba(255, 255, 255, 0.2);
}

.checkbox-label .legend-checkbox:checked ~ .checkmark {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-color: #667eea;
}

.checkmark:after {
  content: "";
  position: absolute;
  display: none;
}

.checkbox-label .legend-checkbox:checked ~ .checkmark:after {
  display: block;
}

.checkbox-label .checkmark:after {
  left: 5px;
  top: 2px;
  width: 4px;
  height: 8px;
  border: solid white;
  border-width: 0 2px 2px 0;
  transform: rotate(45deg);
}

.legend-text {
  color: white;
  font-size: 14px;
}

/* 信息显示样式 */
.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 6px 0;
  font-size: 14px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.info-item:last-child {
  border-bottom: none;
}

.info-label {
  color: rgba(255, 255, 255, 0.8);
}

.info-value {
  color: white;
  font-weight: 600;
}

/* 时间控制样式 */
.control-section h4 {
  margin: 0 0 8px 0;
  font-size: 14px;
  font-weight: 600;
  color: white;
}

.time-controls {
  display: flex;
  flex-direction: row;
  align-items: center;
  gap: 12px;
  flex-wrap: wrap;
}

.control-btn {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 4px 8px;
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.1) 0%, rgba(255, 255, 255, 0.05) 100%);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 6px;
  color: white;
  font-size: 13px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.control-btn:hover:not(:disabled) {
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.15) 0%, rgba(255, 255, 255, 0.1) 100%);
  border-color: rgba(255, 255, 255, 0.3);
}

.control-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.speed-control {
  display: flex;
  align-items: center;
  gap: 8px;
}

.speed-label {
  font-size: 14px;
  color: rgba(255, 255, 255, 0.8);
}

.speed-select {
  padding: 4px 8px;
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 4px;
  color: white;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.speed-select:hover {
  background: rgba(255, 255, 255, 0.15);
  border-color: rgba(255, 255, 255, 0.3);
}

.speed-select option {
  background: #1e293b;
  color: white;
}
</style>